package com.colorful.insuranceproject.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.baoyz.actionsheet.ActionSheet;
import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.bean.DrugAddressBean;
import com.colorful.insuranceproject.utils.StatusBarUtil;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/9/8.
 * <p>
 * 单个定位的Map
 */
public class SingleLocationMapActivity extends TitleActivity implements ActionSheet.ActionSheetListener {
    /**
     * 默认的位置的key
     */
    public static final String EXTRA_DEFAULT_LOCATION = "extra.default.location";

    @Bind(R.id.mv_activity_map)
    MapView mapView;

    @Bind(R.id.tv_address)
    TextView tvAddress;

    @Bind(R.id.tv_details_address)
    TextView tvDetailsAddress;

    private AMap aMap;
    /**
     * 进入默认的位置
     */
    private DrugAddressBean mDefaultLocation;

    @Override
    protected int getContentView() {
        return R.layout.activity_single_location_map;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.transparentAndFullStatusBar(this, true);
        getWindow().getDecorView().setFitsSystemWindows(true);
        if (mapView != null) {
            mapView.onCreate(savedInstanceState);// 此方法必须重写
        }
        init();
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        if (mDefaultLocation != null) {
            if (mDefaultLocation.getLongitude() != -1 && mDefaultLocation.getLatitude() != -1) {
                LatLng ll = new LatLng(mDefaultLocation.getLatitude(), mDefaultLocation.getLongitude());
                changeCamera(
                        CameraUpdateFactory.newCameraPosition(new CameraPosition(
                                ll, 18, 30, 0)));
                aMap.clear();
                aMap.addMarker(new MarkerOptions().position(ll)
                        .icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
            }
        }
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setTitle(getString(R.string.search_map));

        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.icon_dianhua);
        imageView.setId(R.id.call_phone);
        addRightView(imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(mActivity)
                        .setTitle(getString(R.string.hint))
                        .setMessage(mDefaultLocation.getMobile())
                        .setPositiveButton(getString(R.string.call_phone), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mDefaultLocation.getMobile()));
                                startActivity(intent);
                            }
                        }).setNegativeButton(getString(R.string.cancel), null).show();
            }
        });
    }

    @Override
    protected void onInitExtras(@NonNull Bundle bundle) {
        super.onInitExtras(bundle);
        mDefaultLocation = bundle.getParcelable(EXTRA_DEFAULT_LOCATION);
    }

    @Override
    protected void onViewInitialized() {
        tvAddress.setText(getString(R.string.address_desc, mDefaultLocation.getName(), mDefaultLocation.getShopName()));

        tvDetailsAddress.setText(getString(R.string.address_, mDefaultLocation.getAddress()));
    }

    /**
     * 根据动画按钮状态，调用函数animateCamera或moveCamera来改变可视区域
     */
    private void changeCamera(CameraUpdate update) {
        aMap.moveCamera(update);
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    /**
     * 页面监听处理
     */
    @OnClick({R.id.img_go_on, R.id.img_back})
    void OnClicked(View v) {
        switch (v.getId()) {
            case R.id.img_go_on:
                ActionSheet.createBuilder(this, getSupportFragmentManager())
                        .setCancelButtonTitle(getString(R.string.cancel))
                        .setOtherButtonTitles("高德地图", "百度地图", "谷歌地图")
                        .setCancelableOnTouchOutside(true)
                        .setListener(this).show();
                break;
            case R.id.img_back:
                finish();
                break;
        }
    }

    @Override
    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

    }

    @Override
    public void onOtherButtonClick(ActionSheet actionSheet, int index) throws URISyntaxException {
        String lat = String.valueOf(mDefaultLocation.getLatitude());
        String lon = String.valueOf(mDefaultLocation.getLongitude());
        String address = mDefaultLocation.getAddress();
        switch (index) {
            case 0://高德地图 http://blog.csdn.net/lu1024188315/article/details/51780855
                if (isAvilible(this, "com.autonavi.minimap")) {
                    Intent intent = new Intent("android.intent.action.VIEW",
                            android.net.Uri.parse("androidamap://navi?sourceApplication=softname&poiid=BGVIS1&lat=" + lat + "&lon=" + lon + "&dev=0"));
                    intent.setPackage("com.autonavi.minimap");
                    startActivity(intent);
                } else {
                    showMapAlert(getString(R.string.you_cant_install_mipmap), 0);
                }
                break;
            case 1://百度地图 http://lbsyun.baidu.com/index.php?title=uri/api/android#2.5_.E4.BF.A1.E6.81.AF.E6.98.BE.E7.A4.BA
                if (isAvilible(this, "com.baidu.BaiduMap")) {// 驾车路线规划
                    Intent i1 = new Intent();
                    i1.setData(Uri.parse("baidumap://map/direction?&origin=" + lat + "," + lon + "&destination=" + address + "&mode=driving"));
//                    i1.setData(Uri.parse("baidumap://map/direction?region=beijing&origin=" + lat + "," + lon + "&destination=" + address + "&mode=driving"));
                    startActivity(i1);
                } else {
                    showMapAlert(getString(R.string.you_cant_install_baidu_map), 1);
                }
                break;
            case 2://谷歌地图
                if (isAvilible(this, "com.google.android.apps.maps")) {
                    Uri gmmIntentUri = Uri.parse("google.navigation:q=" + address);
                    Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                    mapIntent.setPackage("com.google.android.apps.maps");
                    this.startActivity(mapIntent);
                } else {
                    showMapAlert(getString(R.string.you_cant_install_google_map), 2);
                }
                break;
        }
    }

    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param packageName：应用包名
     */
    private boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    private void showMapAlert(String message, final int type) {
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.hint))
                .setMessage(message)
                .setPositiveButton(getString(R.string.install), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = null;
                        Intent intent = null;
                        switch (type) {
                            case 0:
                                uri = Uri.parse("market://details?id=com.autonavi.minimap");
                                intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                                break;
                            case 1:
                                uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                                intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                                break;
                            case 2:
                                uri = Uri.parse("market://details?id=com.google.android.apps.maps");
                                intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                                break;
                        }
                    }
                }).setNegativeButton(getString(R.string.cancel), null).show();
    }

    @Override
    public void applyTranslationStatusBarAndNavigationBar(boolean showStatusBar, boolean showNavigationBar, int statusBarColor, int navigationBarColor, boolean tint, boolean darkMode) {

    }
}
